﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

namespace Elvex
{
    /// <summary>
    /// AssetBundle更新器
    /// </summary>
    public class AssetBundlesUpdater
    {
        private string m_updateURL;

        public AssetBundlesUpdater(string url)
        {
            m_updateURL = url;
        }

        List<string> m_diffAssetBundles = new List<string>();

        private IEnumerator RequestUpdateConfig()
        {
            var request = UnityWebRequest.Get(m_updateURL);
            yield return request.SendWebRequest();
            if (request.result == UnityWebRequest.Result.ConnectionError ||
                 request.result == UnityWebRequest.Result.ProtocolError)
            {
                Debug.LogError(request.error);
            }
            else
            {
                Debug.Log("获取检验信息成功");
                var ab = AssetBundle.LoadFromMemory(request.downloadHandler.data);
                var manifest = ab.LoadAsset<AssetBundleManifest>("AssetBundleManifest");

                // 获取本地信息
                var localab = AssetBundle.LoadFromFile("");
                var localmanifest = ab.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
                string[] localAssetBundles = localmanifest.GetAllAssetBundles();
                foreach (var item in manifest.GetAllAssetBundles())
                {
                    //if (!Array.Exists(localAssetBundles, (i) => { return i == item; }))
                    //{
                    //    m_diffAssetBundles.Add(item);
                    //    // 源文件不存在下载
                    //    //m_diffFiles.Add(item.Key);
                    //}
                    //else if (manifest.GetAssetBundleHash(item) != localAssetBundles.GetAssetBundleHash(item))
                    //{
                    //    // 文件不一致下载
                    //    m_diffAssetBundles.Add(item);
                    //}
                    //else
                    //{
                    //    // 文件一致
                    //}
                }

                // 加载文件信息


                // 获取文件大小 长度
            }
        }

        private IEnumerator RequestFileManifest()
        {
            var request = UnityWebRequest.Get(m_updateURL);
            yield return request.SendWebRequest();
            if (request.result == UnityWebRequest.Result.ConnectionError ||
                 request.result == UnityWebRequest.Result.ProtocolError)
            {
                Debug.LogError(request.error);
            }
            else
            {
                // 获取更新资源大小

            }
        }

        public void Download()
        {

        }
    }
}
